<?php

/**
 * Controller is the customized base controller class.
 * All controller classes for this application should extend from this base class.
 */
class ApplicationConfig
{

    private static $instance;

    private function __construct()
    {
    }

    public static function app()
    {
        if (!isset(self::$instance))
        {
            $c = __class__;
            self::$instance = new $c;
             
            self::$instance->setParams();
            
            //Yii::app()->components('clientscript', array('class'=>'ext.minScript.components.ExtMinScript'));
            
        }

        return self::$instance;
    }

    public function setParams()
    {
    	    	
    	$array['menus'] = array(
    	'position' => array('1'=>'Header','2'=>'Left','3'=>'Footer')
    	);

    	$array['user'] = array(
    	'permissions' => array()
    	);
    	
    	$array['module'] = array('backup' => 'backup');
    	
    	$array['theme'] = array(
    	'jsUrl' => Yii::app()->theme->baseUrl .'/js/',
    	'cssUrl' => Yii::app()->theme->baseUrl .'/css/', 
    	'imageUrl' => Yii::app()->theme->baseUrl .'/images/',
    	);
    	
    	$array['scaling_params'] = array(
    	'page_template' => array('1'=>'Main'),
    	'basePath'=>str_replace("/frontend/www", "/",str_replace("/backend/www", "/", Yii::app()->getBaseUrl(true))),
    	'status'=>array('1'=>'Enable','0'=>'Disable'),
    	);
		
    	 
    	$array['folder_path'] = array(
    	'uploads' => YiiBase::getPathOfAlias('common.uploads'),
    	
    	//static pages
    	'staticpages' => YiiBase::getPathOfAlias('common.uploads.staticpages'),
    	'staticpagesSmall' => YiiBase::getPathOfAlias('common.uploads.staticpages.small'),
    	'staticpagesMid' => YiiBase::getPathOfAlias('common.uploads.staticpages.mid'),
    	'staticpagesLarge' => YiiBase::getPathOfAlias('common.uploads.staticpages.large'),
    	
    	//banners
    	'banners' => YiiBase::getPathOfAlias('common.uploads.banners'),
    	'bannersSmall' => YiiBase::getPathOfAlias('common.uploads.banners.small'),
    	'bannersMid' => YiiBase::getPathOfAlias('common.uploads.banners.mid'),
    	'bannersLarge' => YiiBase::getPathOfAlias('common.uploads.banners.large'),
    	
    	);

    	$array['url_path'] = array(
    	'staticpagesSmall' => $array['scaling_params']['basePath'].'common/uploads/staticpages/small/',
    	'bannersSmall' => $array['scaling_params']['basePath'].'common/uploads/banners/small/',
    	
    	);
    	
    	
    	$this->params = $array;
    }

    public static function getYearValue($start, $end)
    {
        $yearPass = array();
        for ($i = $start; $i <= $end; $i++)
        {
            $yearPass[$i] = $i;
        }
        return $yearPass;
    }
    public static function getYearValueDescend($start, $end)
    {
        $yearPass = array();
        for ($i = $end; $i >= $start; $i--)
        {
            $yearPass[$i] = $i;
        }
        return $yearPass;
    }

    public static function getMonthValue($start, $end)
    {
        $monthPass = array();
        for ($i = $start; $i <= $end; $i++)
        {
            $monthPass[$i] = $i;
        }
        return $monthPass;
    }

    public static function getSalaryRangeValue($start, $end)
    {
        $monthPass = array();
        for ($i = $start; $i <= $end; $i += 1000)
        {
            $monthPass[$i] = $i;
        }
        return $monthPass;
    }

    public static function getRangeValue($start, $end)
    {
        $monthPass = array();
        for ($i = $start; $i <= $end; $i++)
        {
            $monthPass[$i] = $i;
        }
        return $monthPass;
    }

    public static function getRangeValueNA($start, $end)
    {
        $monthPass = array();
        $monthPass[0] = "NA";
        for ($i = $start; $i <= $end; $i++)
        {
            $monthPass[$i] = $i;
        }
        return $monthPass;
    }

    public static function getDays($start, $end)
    {
        $monthPass = array();
        for ($i = $start; $i <= $end; $i++)
        {
            if ($i == 1)
                $sign = " day";
            else
                $sign = " days";
            $monthPass[$i] = $i . $sign;
        }
        return $monthPass;
    }

    public static function getDaysNA($start, $end)
    {
        $monthPass = array();
        $monthPass[0] = "NA";
        for ($i = $start; $i <= $end; $i++)
        {
            if ($i == 1)
                $sign = " day";
            else
                $sign = " days";
            $monthPass[$i] = $i . $sign;
        }
        return $monthPass;
    }
 
    public static function getURL($module, $controller, $action, $arrParameter =  array(), $config = array())
    {
        $module_name = "";
        $flag = "";
        $flg = "";
        
        if ($module !== "" && isset(ApplicationConfig::app()->params['module'][$module]))
        {
        	
            $module_name = ApplicationConfig::app()->params['module'][$module] . "/";
        }
		
        $url = $module_name . $controller . "/" . $action . "/";

        if ($controller == "" && $module == "")
        {
            $url = $action . "/";
        }
        foreach ($arrParameter as $key => $val)
        {
            if (empty($key))
            {
                $flag = 1;
                $value = $val;
            }
            if ($key == 'spcbrands')
            {
                $flg = 2;
                $value2 = $val;
            }
        }
        if ($flag == 1 && empty($flg))
        {
            $url = $action . "/" . $value;
            return Yii::app()->createUrl($url);
        } else
            if ($flg == 2)
            {
                $url = $action . "/" . $value2 . "/" . $value;
                return Yii::app()->createUrl($url);
            } else
            {
                return Yii::app()->createUrl($url, $arrParameter);
            }

    }


    public static function getConstantData($type)
    {
        $arrReturn = array();
        switch ($type)
        {
            case 'USER-TYPE':
                $arrReturn = array('client' => 'Client', 'company' => 'Company');
                break;

            case 'CURRENCY':
                $arrReturn = array('US' => 'US', 'EURO' => 'EURO');
                break;
        }
        return $arrReturn;
    }

    public static function truncateString($text, $nbrChar, $append = '...')
    {
        if (strlen($text) > $nbrChar)
        {
            $text = substr($text, 0, $nbrChar);
            $text .= $append;
        }
        return $text;
    }


    public static function getServerName()
    {
        return isset(Yii::app()->request->serverName) ? Yii::app()->request->serverName : null;
    }


    public static function sendmail($recievermail, $recievername, $subject, $htmlmsg)
    {
        Yii::import('application.extensions.phpmailer.JPhpMailer');
        $mail = new JPhpMailer;
        $mail->IsSMTP();
        $mail->Mailer = "smtp";
        $mail->SMTPSecure = "ssl";  
        $mail->Host='smtp.gmail.com';  
        $mail->Port='465';   
        $mail->SMTPAuth = true;
        $mail->Username = "indianidoltest@gmail.com"; // GMAIL username
        $mail->Password = "idol@2013"; // GMAIL password
        $mail->SetFrom("indianidoltest@gmail.com",'indianidol');
        $mail->Subject = "User Registration msg" ;
        $mail->MsgHTML('<h1>JUST A TEST!</h1>');
        $mail->AddAddress("indianidoltest@gmail.com","web registration"); 
        
        $mail->Subject =$subject;
        $mail->MsgHTML($htmlmsg);
        $mail->AddAddress($recievermail,$recievername);
        $mail->Send();

    }

    public static function deleteDir($dirPath)
    {
        if (!is_dir($dirPath))
        {
            throw new InvalidArgumentException('$dirPath must be a directory');
        }
        if (substr($dirPath, strlen($dirPath) - 1, 1) != '/')
        {
            $dirPath .= '/';
        }
        $files = glob($dirPath . '*', GLOB_MARK);
        foreach ($files as $file)
        {
            if (is_dir($file))
            {
                self::deleteDir($file);
            } else
            {
                unlink($file);
            }
        }
        if ($dirPath != YiiBase::getPathOfAlias('webroot.assets') . '/' && $dirPath != YiiBase::getPathOfAlias('backend.runtime') . '/')
            rmdir($dirPath);
    }
    public static function deleteFile($dirPath, $filename)
    {
        if (!is_dir($dirPath))
        {
            throw new InvalidArgumentException('$dirPath must be a directory');
        }
        if (substr($dirPath, strlen($dirPath) - 1, 1) != '/')
        {
            $dirPath .= '/';
        }
        $files = glob($dirPath . '*', GLOB_MARK);
        foreach ($files as $file)
        {
            if (is_dir($file))
            {
                self::deleteFile($file, $filename);
            } else
            {
                //echo $file." ------------------";
                //echo $dirPath.$filename."<br/>";
                if ($file == $dirPath . $filename)
                {
                    if (unlink($file))
                        echo "deleted successfully";
                    else
                        echo "Error occured. Please check file name and try again.";
                }
            }
        }

    }
    public static function ArryMovetoTop($array, $key)
    {
        $temp = array($key => $array[$key]);
        unset($array[$key]);
        $array = $temp + $array;
        return $array;
    }
    public static function getSystemUrl()
    {
        $s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
        $sp = strtolower($_SERVER["SERVER_PROTOCOL"]);
        $protocol = substr($sp, 0, strpos($sp, "/")) . $s;
        $port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":" . $_SERVER["SERVER_PORT"]);
        $host = (isset($_SERVER['HTTP_HOST']) && !empty($_SERVER['HTTP_HOST'])) ? $_SERVER['HTTP_HOST'] :
            $_SERVER['SERVER_NAME'];
        return $protocol . "://" . $host . $port . $_SERVER['REQUEST_URI'];
    }
    public static function findAge($bMonth, $bDay, $bYear)
    {
        list($cYear, $cMonth, $cDay) = explode("-", date("Y-m-d"));
        return (($cMonth >= $bMonth && $cDay >= $bDay) || ($cMonth > $bMonth)) ? $cYear -
            $bYear : $cYear - $bYear - 1;
    }
    public static function getPathSegments($url)
    {
        $parts = explode('/', $url);
        //var_dump($parts);exit;
        $last = "";
        foreach ($parts as $key => $value)
        {
            if ($key != 0 && $key != 1 && $key != 2)
            {

                if ($value == "compete")
                    $value = "Competitions";
                if (!empty($value))
                    $last .= " | " . ucfirst($value);
            }

        }
        if ($last == "")
            $last = " | Home";

        return $last; // get the last segment
    }
   
 
    public static function dateDifference($start, $end)
    {

        $start_ts = strtotime($start);

        $end_ts = strtotime($end);

        $diff = $end_ts - $start_ts;

        return round($diff / 86400);

    }
    
 public static function moduleList()
    {
		$moduleName = array();
		$modules = Yii::app()->getModules();
		foreach ($modules as $key => $value){
			if($key!="gii"){
				$moduleName[$key] = $key;
			}	
		}
		return $moduleName;

    }

    public  static function getMenu()
    {
	    $menuName = array();
    	$menu= Menus::model()->getList("BACKEND", array('main_menuID'=>1));

		foreach ($menu as $key1 => $value1)
        {
            		if($value1->parentID==0)
            		{
            			$child = self :: getChild($menu, $value1->menuID);
                        //echo "<pre>";print_r($child);exit;
                        if (!empty($child)){
                            foreach ($child as $key => $value) {
                                if($value['visible'] == 1){
                                    $visible = 1;
                                    break;
                                }else{
                                    $visible = 0;
                                }
                            }
                        }
                        else
                        {
                            $visible = self::getMenuVisiblity($value1->system_url);            			     
                        }
                        $menuName[] = array('url'=>Yii::app()->getBaseUrl(true) .$value1->system_url, 'label'=>$value1->menu_name, 'visible'=>$visible,'items' => $child );
            	        
            		}			
		}
       //echo "<pre>";print_r($menuName);exit;
      
		
		return $menuName;
    }
    
	public static function getChild($menu, $id)
    {
    	$items = array();
	
		foreach ($menu as $key => $value){
			if($value->parentID == $id)
			{
				
				$subchild = array();
				
						foreach ($menu as $key1 => $value1)
						{
								
							if($value1->parentID == $value->menuID)
							{								
								$subchild[] = array('url'=>Yii::app()->getBaseUrl(true) .$value1->system_url, 'label'=>$value1->menu_name, 'visible'=>self::getMenuVisiblity($value1->system_url));
								
							}
							
						}
				$items[] = array('url'=>Yii::app()->getBaseUrl(true) .$value->system_url, 'label'=>$value->menu_name, 'visible'=>self::getMenuVisiblity($value->system_url),'items' => $subchild);
				
			}
		}
		//print_r($items);exit;
		return $items;
	}

    public static function getMenuVisiblity($sysurl, $id = null)
    {
	    if(Yii::app()->user->isGuest) {
    		return 0;
    	}
    	else 
    	{
            $role_menu = ApplicationSessions::run()->read('permissions');
		//echo "<pre>";print_r($role_menu);exit;
            if(!empty($role_menu))
            {
                $role_menu = explode(",",str_replace('.','/',strtolower($role_menu[0])));
    			
                if(in_array(strtolower($sysurl), $role_menu))
                {
                    return 1;
                }
                else
                {
                    return 0;
                }
            }else
                return 0;
    	}
    }

    public function getFormattedDate($date)
    {
        $date = strtotime($date);
        $date = date("d-M-Y h:m A", $date);
        return $date;
    }

    public function getMinuteSeconds($millisec)
    {
        $seconds = floor($millisec/1000);
        $minutes = floor($seconds/60);
        $seconds = $seconds % 60;
        if($minutes<10)
            $minutes = "0".$minutes;
        if($seconds<10)
            $seconds = "0".$seconds;
        $res = $minutes.":".$seconds;
        return $res;
    }
    
	public function getBannerWidgets($module=null,$include_classes=false)
    {

        if ($module!=null){
            $path=join(DIRECTORY_SEPARATOR,array(Yii::app()->modulePath,$module,'widgets'));
        }else{
            $path='frontend'.DIRECTORY_SEPARATOR.'widgets';
        }                
		
        $files = scandir($path);
        //print_r($files);exit;
        
        $widgets=array();
        foreach ($files as $f)
        {
            if (stripos($f,'.php')!==false)
            {
            	$widget_name = str_ireplace('.php','',$f);
            	if (strpos($widget_name, 'B_') !== false){
	                $widgets[$widget_name] = $widget_name;
	                if ($include_classes)
	                {
	                    include_once($path.DIRECTORY_SEPARATOR.$f);
	                } 
            	}

            }
        }       
        return $widgets; 

    }
    public static function DOBinYears($dob)
    {
        return floor((strtotime(date('d-m-Y')) - strtotime($dob))/(60*60*24*365.2421896));
    }

    public static function getUserLocationByIp()
    {
    		$value =  ApplicationSessions::run()->read('ip_location');
    		if (empty($value)){
    		$ipAddress = '';
        		foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key)
					{
					    if (array_key_exists($key, $_SERVER) === true)
					    {
					        foreach (explode(',', $_SERVER[$key]) as $ip)
					        {
					            if (filter_var($ip, FILTER_VALIDATE_IP) !== false)
					            {
					                $ipAddress = $ip;
					                break;
					            }
					        }
					    }
					}
					
				$result = file_get_contents("http://api.ipinfodb.com/v3/ip-country/?key=c7f73279336e9ac9b02b1b6e04277272f84bfc5c9449ccc9b94711d3cb0c6abe&ip=5.135.99.132");
				
				$result = explode(";", $result);
				$result = $result[count($result)-1];
				$result = strtolower($result);
				$ukcountries = array('england','scotland','wales','ireland');
			    if (in_array($result, $ukcountries))
			    {
			    	$value = "uk";
			    }
			    else 
			    $value = "in";
			   ApplicationSessions::run()->write('ip_location',$value);
    		}
			    return $value;
				
    }
    
    function sort_array($array, $key) 
	{
		/*sort multidimetional array according to key */
		
	    $sorter=array();
	    foreach ($array as $ii => $va) {
	        $sorter[$va[$key]]=$va;
	    }
	    ksort($sorter);
		//var_dump($sorter);exit;
	    
	    
	   return $sorter;
	}
	
	 public function createDateRangeArray($strDateFrom,$strDateTo)
	{
		    // takes two dates formatted as YYYY-MM-DD and creates an
		    // inclusive array of the dates between the from and to dates.
		
		    // could test validity of dates here but I'm already doing
		    // that in the main script
		
		    $aryRange=array();
		
		    $iDateFrom=mktime(1,0,0,substr($strDateFrom,5,2),     substr($strDateFrom,8,2),substr($strDateFrom,0,4));
		    $iDateTo=mktime(1,0,0,substr($strDateTo,5,2),     substr($strDateTo,8,2),substr($strDateTo,0,4));
		
		    if ($iDateTo>=$iDateFrom)
		    {
		        array_push($aryRange,date('Y-m-d',$iDateFrom)); // first entry
		        while ($iDateFrom<$iDateTo)
		        {
		            $iDateFrom+=86400; // add 24 hours
		            array_push($aryRange,date('Y-m-d',$iDateFrom));
		        }
		    }
		    return $aryRange;
	}
		
	public static function encrypting($string="") {
		$hash = 'md5';
		if ($hash=="md5")
			return md5($string);
		if ($hash=="sha1")
			return sha1($string);
		else
			return hash($hash,$string);
	}
    
}